package ele_handler

import (
	"fmt"
	"go-yuque/logger"
	"golang.org/x/net/html"
	"strings"
)

func init() {

	registerInitFunc(
		func() YuqueElementHandler {
			y := &cardYuqueStruct{}
			y.elements = []string{"card"}
			y.attributes = map[string]string{"name": "yuque"}
			return y
		})
}

type cardYuqueStruct struct {
	BaseHandler
	Mode       string `json:"mode"`
	HeightMode string `json:"heightMode"`
	Src        string `json:"src"`
	URL        string `json:"url"`
	Detail     struct {
		Image      string `json:"image"`
		Title      string `json:"title"`
		Type       string `json:"type"`
		Belong     string `json:"belong"`
		BelongURL  string `json:"belong_url"`
		Desc       string `json:"desc"`
		URL        string `json:"url"`
		TargetType string `json:"target_type"`
		Serializer string `json:"_serializer"`
	} `json:"detail"`
	ID     string `json:"id"`
	Margin struct {
		Top    bool `json:"top"`
		Bottom bool `json:"bottom"`
	} `json:"margin"`
}

func (y *cardYuqueStruct) doHandle() (err error) {

	err = parseCardJson(y.node, y)
	if err != nil {
		logger.Errorf("[cardYuque]解析异常")
		sb := strings.Builder{}
		err = html.Render(&sb, y.node)
		if err != nil {
			y.WriteTextContext(sb.String())
		}
		return
	}

	if len(y.Src) <= 0 || len(y.Detail.Title) <= 0 {
		logger.Errorf("[cardYuque]参数为空")
		return fmt.Errorf("参数为空")
	}

	y.WriteTextContext(fmt.Sprintf("引用语雀文档:[%s](%s)\n\n", y.Detail.Title, y.Src))

	return
}
